const Sequelize = require('sequelize')
const db = require('./db')
const Category = require('./Category')
const Tag = require('./Tag')
const ArticleTag = require('./ArticleTag')

// 将allowNull设置为false会将NOT NULL添加到列中，
const Article = db.define(
  'article',
  {
    id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false },
    name: { type: Sequelize.STRING, allowNull: false },
    category_id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      references: {
      // 这是引用另一个模型
        model: Category,
        // 这是引用模型的列名称
        key: 'id'
      }
    },
    tag: {type: Sequelize.INTEGER, allowNull: false},
    created_at: {
      type: Sequelize.DATE,
      defaultValue: Sequelize.NOW,
      allowNull: false
    },
    updated_at: {
      type: Sequelize.DATE,
      defaultValue: Sequelize.NOW,
      allowNull: false
    }
  },
  {
    // 如果为 true 则表的名称和 model 相同，即 user
    // 为 false MySQL创建的表名称会是复数 users
    // 如果指定的表名称本就是复数形式则不变
    // freezeTableName: true,
    timestamps: false
  }
)
Article.belongsTo(Category)
Article.Tags = Article.hasMany(Tag)
Article.sync({ force: false })
  .then(res => {
    console.log('create table successfully!')
  })
  .catch(err => {
    console.log('create table error!', err)
  })

module.exports = Article
